package cn.mesmile.juc.assist.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author zb
 * @date 2022/1/23 12:12
 * @Description
 */
public class SemaphoreDemo2 {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);
        Semaphore semaphore2 = new Semaphore(1);
        Semaphore semaphore3 = new Semaphore(1);

        try {
            // 认证 类似于睡眠
            semaphore2.acquire();
            semaphore3.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            while (true) {
                try {
                    semaphore2.acquire();
                    Thread.sleep(100);
                    System.out.println("B");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    // 释放 类似于唤醒
                    semaphore3.release();
                }
            }
        },"线程二").start();

        new Thread(() -> {
            while (true) {
                try {
                    semaphore.acquire();
                    Thread.sleep(100);
                    System.out.println("A");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore2.release();
                }
            }
        },"线程一").start();

        new Thread(() -> {
            while (true){
                try {
                    semaphore3.acquire();
                    Thread.sleep(100);
                    System.out.println("C");
                    System.out.println("-------------------------------------------");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            }
        },"线程三").start();

    }
}
